import { watch, unref } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useTitle as usePageTitle } from '@vueuse/core';
import { useGlobSetting } from '/@/hooks/setting';
import { useRouter } from 'vue-router';
import { useLocaleStore } from '/@/store/modules/locale';
import { useUserStore } from '/@/store/modules/user';
import { useAppStoreWithOut } from '/@/store/modules/app';
import { useMultipleTabStore } from '/@/store/modules/multipleTab';

import { REDIRECT_NAME } from '/@/router/constant';

/**
 * Listening to page changes and dynamically changing site titles
 */
export function useTitle() {
  const { title } = useGlobSetting();
  const { t } = useI18n();
  const { currentRoute } = useRouter();
  const localeStore = useLocaleStore();
  const userStore = useUserStore();

  const pageTitle = usePageTitle();

  watch(() => userStore.getUserCurrentProjectCode, () => {
    useAppStoreWithOut().clearMenuRoute();
    const tabStore = useMultipleTabStore();
    tabStore.resetState();
    let project = userStore.getUserValidProjects?.find((item) => item.objcode == userStore.getUserCurrentProjectCode)
    if (project) userStore.setUserCurrentProject(project);
  }, { immediate: true },)

  watch(
    [() => userStore.getUserCurrentProject, () => currentRoute.value.path, () => localeStore.getLocale],
    () => {
      const route = unref(currentRoute);
      if (route.name === REDIRECT_NAME) {
        return;
      }
      //获取路由中配置的名称，当前页面标题名称
      const tTitle = t(route?.meta?.title as string);
      //页面显示的标题格式为：页面名称-系统名称
      //系统名称默认使用env中的title，如果有设置项目fulltitle或title使用项目中的配置
      let systemName = title;
      //获取系统标题名称，先从store中获取，如果store中没有再去env中配置的标题
      const currentProject = userStore.getUserCurrentProject;
      // alert(JSON.stringify(currentProject), 'currentProject')
      if (currentProject != undefined && currentProject != null) {
        // console.log('hooks userTitle currentProject', currentProject);
        //取store中当前项目信息的values，按对象方式取值
        if (currentProject.values != undefined && currentProject.values != null) {
          let fulltitleValue = currentProject.values.fulltitle;
          // fulltitleValue = currentProject.values["fulltitle"];
          if (fulltitleValue != undefined && fulltitleValue != null && fulltitleValue != '') {
            systemName = fulltitleValue;
          }
          else {
            let titleValue = currentProject.values.title;
            // titleValue = currentProject.values["title"];
            if (titleValue != undefined && titleValue != null && titleValue != '') {
              systemName = titleValue;
            }
          }
        }
      }
      pageTitle.value = tTitle ? ` ${tTitle} - ${systemName} ` : `${systemName}`;
    },
    { immediate: true },
  );
}
